using System;

namespace CloudClipboardSync
{
    public class ClipboardChangeListener: IDisposable
    {
        private readonly WndProcHandler wndProcHandler;
        private IntPtr nextClipboardViewer;

        public event EventHandler ClipboardChanged;

        public ClipboardChangeListener()
        {
            wndProcHandler = new WndProcHandler();
            wndProcHandler.WindowMessageReceived += WindowMessageReceived;
            nextClipboardViewer = (IntPtr)WinApi.SetClipboardViewer(wndProcHandler.Handle);
        }

        public void WindowMessageReceived(IntPtr hwnd, uint uMsg, uint wparam, uint lparam)
        {
            if(uMsg == WinApi.WM_DRAWCLIPBOARD)
            {
                ClipboardChanged.SafeInvoke(this, EventArgs.Empty);
                WinApi.SendMessage(nextClipboardViewer, uMsg, wparam, lparam);                
            } 
            else if(uMsg == WinApi.WM_CHANGECBCHAIN)
            {
                if (wparam == (uint)nextClipboardViewer)
                    nextClipboardViewer = (IntPtr)lparam;
                else
                    WinApi.SendMessage(nextClipboardViewer, uMsg, wparam, lparam);                
            }
        }

        public void Dispose()
        {
            WinApi.ChangeClipboardChain(wndProcHandler.Handle, nextClipboardViewer);
            wndProcHandler.Dispose();
        }
    }
}